using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;
using PHSRAG.WebControls;
using Forms = PHSRAG.Insight21.FormsManagement;
using webControls=PHSRAG.WebControls;
using PageHeader = PHSRAG.Insight21.InsightWebControls.Header;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// Summary description for ProtocolProcessOverview.
    /// </summary>
    public partial class ProtocolProcessOverview : BasePage
    {
        #region Instance Vars.

        private const string DeleteConfirmationFlag = "deleteConfirmFlag";
        private ICachePolicy applicationCachePolicy;
        private ICachePolicy cachePolicy;
        private bool confirmDelete = false;
        private ProtocolVersion currentVers;
        private ProtocolProcess currProcess;
        private Protocol currProtocol;
        private ArrayList gridArrayList;
        private Hashtable pageCache;
        private ICachePolicy pageCachePolicy;
        private int protocolId;
        private int protocolProcessId;

        //This flag is used to decide whether or not the headers should be displayed
        //If the page is to be displayed as a popup, then the header section is made invisible
        private bool showAsPopUp = false;
        private int userAccessLevel;
        private ViewStateCachePolicy viewStateCachePolicy;

        #endregion

        #region Constants

        private const string PageCacheKey = "protocolProcessOverviewPage__7C687A52-0C4D-42e2-A4BE-9245BD3DA005";
        private const string ProtocolAccessLevelKey = "protocolAccessLevel_1F050E42-EE0C-4d6d-9059-7DA46C2DEE3A";
        private const string ProtocolIdKey = "protocolId_968F0F26-1258-49e9-A1B0-ADA426D2E28A";
        private const string ProtocolProcessIdKey = "protocolProcessId_26D4E4B5-97DE-4176-83A9-9E8AE2B0B8BF";
        private const string QuestionnaireListKey = "questionnaireList_76250C76-F1BE-4db5-BB11-DD5BF2BF93CC";
        private const string ReferringPageKey = "ReferringPageKey_A0DD1B95-A0FF-4783-8A96-0B65A55E6923";
        private const string SponsorQuestionnaireName = "Sponsor Funding";

        #endregion

        #region private properties

        /// <summary>
        /// Gets the protocol .If it's not already in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                currProtocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((currProtocol == null) || (protocolId != currProtocol.Id))
                {
                    currProtocol = new Protocol(cachePolicy);
                    currProtocol.Load(DataAccess.GetConnectionString(), protocolId);
                    cachePolicy.Cache(cacheKey, currProtocol);
                }
                return currProtocol;
            }
        }

        /// <summary>
        /// Gets the protocol process . If it's not already
        /// in the cache, it loads it up based on the protocolProcessId passed to the page, and caches the 
        /// object
        /// </summary>
        private ProtocolProcess ProtocolProcess
        {
            get
            {
                currProcess = cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey)
                    as ProtocolProcess;

                if ((currProcess == null) || (protocolProcessId != currProcess.Id))
                {
                    if (protocolProcessId != 0)
                    {
                        currProcess = ProtocolProcess.GetProtocolProcess(
                            DataAccess.GetConnectionString(), protocolProcessId, cachePolicy, null);
                        cachePolicy.Cache(ProtocolProcess.ProtocolProcessKey, currProcess);
                    }
                    else
                    {
                        currProcess = null;
                    }
                }
                return currProcess;
            }
        }

        private ProtocolVersion ProtocolVersion
        {
            get
            {
                if (currentVers == null)
                {
                    if (ProtocolProcess != null)
                    {
                        currentVers = currProcess.GetLatestProtocolVersion(true, cachePolicy);
                        // If we just created a new version, save it here so the cloned QAs
                        // have valid Ids, otherwise orphaned QAs get saved.
                        if (currentVers.Version > currProcess.LastLockedVersion)
                            currentVers.Save(Utility.DataAccess.ConnectionString);
                    }
                    else
                    {
                        currentVers = new ProtocolVersion(cachePolicy);
                        currentVers = (ProtocolVersion) cachePolicy.GetCachedObject(currentVers.CacheKey());
                    }
                    currentVers.Cache();
                }
                return currentVers;
            }
        }

        /// <summary>
        /// Get and Set the referring page that brought us to the PODetails page. Using the value for the referring
        /// page, the navigation bars to be displayed on this page is decided.
        /// </summary>
        private string ReferringPage
        {
            get
            {
                object o = viewStateCachePolicy.GetCachedObject(ReferringPageKey);
                return (o == null) ? string.Empty : (string) o;
            }
            set { viewStateCachePolicy.Cache(ReferringPageKey, value); }
        }

        #endregion

        protected void OnPageLoad(object sender, EventArgs e)
        {
            deleteApp.Attributes.Add("onClick", "return ConfirmDelete();");

            try
            {
                breadCrumb.Add(
                    "Forms",
                    Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolProcessOverviewURL", ""),
                    Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

                pageCache = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();

                string formData = Request.Form[DeleteConfirmationFlag];
                confirmDelete = (formData != null && formData == "True");
                if (header.ModuleName.ToLower() == "animals")
                {
                    editProtocolInfo.Text = "Full title";
                }
                if (!IsPostBack)
                {
                    /*Check for the availability of the listpage Url(eg: workinprogress,pendingApplication etc)
					* Level=1 -->holds the top level page Url like workinprogress,pedingApplications etc(To which the page should be redirected to, on deleting the protocol/Process)
					*/
                    ArrayList breadCrumbs = breadCrumb.BreadCrumbDetails;
                    foreach (BreadCrumbInfo breadcrumbInfo in breadCrumbs)
                    {
                        if (breadcrumbInfo.Level == 1)
                        {
                            ReferringPage = ((BreadCrumbInfo) (breadCrumbs[0])).NavigateUrl;
                            break;
                        }
                    }
                 
                    /*Trackit 10010. The ReferringPage check is commented out for the HF release of 2.3+DM
                     * There is another trackit ticket to fix the breadcrumbs issues as part of 2.3.1
                     */
                    //Throw exception if the above stepcould not find the top level page
                    //if(ReferringPage==string.Empty)
                    //{
                    //    throw new Exception("Unable to find the top level page");
                    //}

                    Hashtable incomingPageHash =
                        pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    if (incomingPageHash != null)
                    {
                        protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);

                        // Load the protocol Process from the ID.
                        protocolProcessId = Convert.ToInt32(incomingPageHash[Keys.ProtocolProcessIdKey]);

                        if (incomingPageHash.ContainsKey(Keys.ShowAsPopUp))
                        {
                            showAsPopUp = Convert.ToBoolean(incomingPageHash[Keys.ShowAsPopUp]);
                        }


                        if (ProtocolProcess != null)
                        {
                            // get security level- todo: change this as part of #4045.
                            userAccessLevel = Convert.ToInt32(incomingPageHash[Keys.ProtocolAccessKey]);

                            // cache the ProtocolProcess
                            currProcess.Cache();
                            
                            // check the status of the process - if it's WIP or Submitted and the user has manage,
                            // then display the button. OR (new rule for 2.1.3) if the user has edit privileges and
                            // is the submitter  
                            // Need to make deleteApp button visible before it moves to rex                           
                            if (!showAsPopUp && ((userAccessLevel & Protocol.ManagePermission) > 0
                                    || currProcess.SubmitterId == ((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).DomainUserId)
                                      && (ProtocolProcess.MovedToRex == 0))
                                deleteApp.Visible = true;
                            else
                                deleteApp.Visible = false;
                            

                            // disable button if user only has view
                            if (!((userAccessLevel & Protocol.ManagePermission) > 0)
                                && !((userAccessLevel & Protocol.EditPermission) > 0))
                            {
                                addDeleteForms.Visible = false;
                                editProtocolInfo.Visible = false;
                                editProtocolInfoStatic.Visible = false;
                            }

                            if (ProtocolProcess.Type !=
                                Constants.ProtocolProcessType.InitialReview &&
                                    ProtocolProcess.Type != Constants.AnimalProtocolProcessType.InitialReview)
                            {
                                editProtocolInfo.Visible = editProtocolInfoStatic.Visible = false;
                            }
                        }
                        pageCache[Keys.ShowAsPopUp] = showAsPopUp;
                        pageCache[ProtocolAccessLevelKey] = userAccessLevel;
                        pageCache[ProtocolIdKey] = protocolId;
                        pageCache[ProtocolProcessIdKey] = protocolProcessId;

                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }
                    else
                    {
                        protocolId = (int) pageCache[ProtocolIdKey];
                        protocolProcessId = (int) pageCache[ProtocolProcessIdKey];
                        showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                        userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                    }
                    if (ProtocolProcess != null)
                    {
                        // now build the array list of the objects we want to bind to the grid.
                        gridArrayList = PopulateGridQuestionnaireList( );

                        pageCache[QuestionnaireListKey] = gridArrayList;
                        pageCachePolicy.Cache(PageCacheKey, pageCache);

                        formsGrid.DataSource = gridArrayList;
                        formsGrid.DataBind();
                    }
                }
                else
                {
                    protocolId = (int) pageCache[ProtocolIdKey];
                    protocolProcessId = (int) pageCache[ProtocolProcessIdKey];
                    showAsPopUp = (bool) pageCache[Keys.ShowAsPopUp];
                    userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];

                    // disable button if user only has view
                    if ((userAccessLevel & Protocol.ManagePermission) > 0)
                    {
                        addDeleteForms.Visible = true;
                    }

                    if (protocolProcessId > 0)
                    {
                        gridArrayList = (ArrayList) pageCache[QuestionnaireListKey];
                    }
                }

                //if page is being shown as popup, then hide the header section

                // only enable the Add/Delete forms and Delete App button if this is a 
                // STANDARD PROTOCOL's InitialReview 
                if (Protocol.ProtocolTypeCode == Constants.NewProtocolType.EmergencyApp ||
                    ProtocolProcess.Type != Constants.ProtocolProcessType.InitialReview &&
                        ProtocolProcess.Type != Constants.AnimalProtocolProcessType.InitialReview &&
                            ProtocolProcess.Type != Constants.AnimalProtocolProcessType.Deficiency)
                {
                    addDeleteForms.Visible = false;
                }

                headerSection.Visible = !showAsPopUp;

                SetupPageForModuleType();
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
                formsGrid.Enabled = false;
                addDeleteForms.Visible = false;
                deleteApp.Enabled = false;
            }
            finally
            {
                // set the header's protocol details.	
                protocolDetailHeader.ProtocolID = protocolId;
            }
        }

        /// <summary>
        /// Make necessary changes to page for use by Animals or Humans
        /// </summary>
        protected void SetupPageForModuleType()
        {
            if (Protocol.ModuleType == Constants.ModuleType.Animals)
            {
                animalsSubModNavigation.Visible = true;
                humansSubModNavigation.Visible = false;
                animalsSubModNavigation.ProtocolProcess = ProtocolProcess;
                animalsSubModNavigation.Protocol = Protocol;
                animalsSubModNavigation.SelectedLink = "Forms";
                cloneControls.Visible = true;
                bool bIRFound = false;
                foreach (ProtocolProcess process in Protocol.ProtocolProcesses)
                {
                    if (process.Type == Constants.AnimalProtocolProcessType.InitialReview)
                    {
                        bIRFound = true;
                    }
                }
                if (!bIRFound)
                {
                    cloneProtocol.ImageUrl = "~/Images/b_cloneprotocol_disabled.gif";
                    cloneProtocol.Enabled = false;
                    cloneControls.Attributes["style"] = "width:150px;border:solid 2px #808080";
                    cloneOptions.Enabled = false;
                }
            }
            else
            {
                //Set the Human sub mod Navigation links
                humansSubModNavigation.Visible = true;
                animalsSubModNavigation.Visible = false;
                humansSubModNavigation.ProtocolProcess = ProtocolProcess;
                humansSubModNavigation.Protocol = Protocol;
                humansSubModNavigation.SelectedLink = "Forms";
            }
        }

        /// <summary>
        /// OnItemDataBound is fired when the forms array list is bound to the grid. In the case 
        /// of a header row (the categories of the forms), the font and color of the 
        /// bar are changed to reflect the grouping.
        /// </summary>
        /// <param name="sender">The control which raised the event.</param>
        /// <param name="e">Arguments assocoiated with the event</param>
        private void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    if (e.Item.Cells[(int) ColumnIndex.Id].Text == "-1")
                    {
                        TableCell groupHeader = e.Item.Cells[(int) ColumnIndex.SelectForm];
                        string dataValue = ((LinkButton) groupHeader.Controls[0]).Text;
                        groupHeader.Controls.Clear();
                        groupHeader.Controls.Add(new LiteralControl(dataValue));
                        groupHeader.Font.Bold = true;
                        groupHeader.BackColor = Color.Orange;
                        e.Item.Cells[(int) ColumnIndex.LastModifiedDate].Text = string.Empty;
                        e.Item.Cells[(int) ColumnIndex.FormAction].Controls[1].Visible = false;
                    }
                    else if (!((userAccessLevel & Protocol.ManagePermission) > 0)
                        && !((userAccessLevel & Protocol.EditPermission) > 0))
                    {
                        TableCell groupHeader = e.Item.Cells[(int) ColumnIndex.SelectForm];
                        string dataValue = ((LinkButton) groupHeader.Controls[0]).Text;
                        groupHeader.Controls.Clear();
                        groupHeader.Controls.Add(new LiteralControl(dataValue));
                        e.Item.Cells[(int) ColumnIndex.FormAction].Controls[1].Visible = false;
                    }
                    if (ProtocolProcess.Type == Constants.ProtocolProcessType.Amendment ||
                        ProtocolProcess.Type == Constants.AnimalProtocolProcessType.Amendment
                            || ProtocolProcess.Type == Constants.AnimalProtocolProcessType.TriennialReview)
                    {
                        LinkButton button = e.Item.Cells[(int) ColumnIndex.SelectForm].Controls[0] as LinkButton;
                        if (button != null)
                        {
                            if (button.Text == "Amendment" || button.Text == "IACUCAmendment" ||
                                button.Text == "Triennial Review" ||
                                    (button.Text == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.MedicalDevices) ||
                                        (button.Text == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Drugs) ||
                                            (button.Text == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR) ||
                                                (button.Text == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM) ||
                                                    (button.Text == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Children) ||
                                                        (button.Text == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous) ||
                                                            (button.Text == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures) ||
                                                                (button.Text == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Anesthesia) ||
                                                                    (button.Text == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor) ||
                                                                        (((QuestionnaireAnswer) (e.Item.DataItem)).Required))
                            {
                                e.Item.Cells[(int) ColumnIndex.FormAction].Controls[1].Visible = false;
                            }
                            else
                            {
                                QuestionnaireAnswer answer =
                                    (QuestionnaireAnswer) e.Item.DataItem;
                                string action = answer.Action.ToString();
                                RadioButtonList actions =
                                    (RadioButtonList) e.Item.Cells[(int) ColumnIndex.FormAction].Controls[1];
                                actions.SelectedValue = action;
                                button.Enabled =
                                    (action == ((int) QuestionnaireAnswer.UserAction.Edit).ToString());
                                // if this is a new QuestionnaireAnswer, it doesn't make sense for the user to
                                // select "No Change" so we will hide this option
                                if (!answer.IsClone)
                                {
                                    actions.Items.Remove(actions.Items.FindByValue(
                                        ((int) QuestionnaireAnswer.UserAction.NoChange).ToString()));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
                formsGrid.Enabled = false;
                addDeleteForms.Visible = false;
                deleteApp.Enabled = false;
            }
        }

        /// <summary>
        /// Shows the form action column for amendments 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnDataBound(object sender, EventArgs e)
        {
            formsGrid.Columns[(int) ColumnIndex.FormAction].Visible =
                (ProtocolProcess.Type == Constants.ProtocolProcessType.Amendment ||
                    ProtocolProcess.Type == Constants.AnimalProtocolProcessType.Amendment ||
                        ProtocolProcess.Type == Constants.AnimalProtocolProcessType.TriennialReview);
        }

        /// <summary>
        /// Construct an array list of QuestionnaireAnswers that is to be displayed in 
        /// the grid, broken out by Questionnaire type (the heading). Add in Heading rows for any
        /// appropriate Questionnaires that this PV contains, based on the Req script.
        /// </summary>
        private ArrayList PopulateGridQuestionnaireList( )
        {

            ArrayList answerList = ProtocolVersion.QuestionnaireAnswers;
            string processType = currProcess.Type;
            ArrayList gridArrayList = new ArrayList();

            try
            {
                // first add the InitialQuestionnaire in if it's not a STANDARD PROTOCOL IR.
                if (processType != Constants.ProtocolProcessType.InitialReview || 
                    Protocol.ProtocolTypeCode == Constants.NewProtocolType.EmergencyApp)
                {
                    // get the Ref Codes, and add them one by one, along with any in teh Answer List.
                    RefCodes refCodes = (RefCodes) applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);

                    // TODO: Case the appropriate domain here...
                    string processTypeDomain;

                    switch (processType)
                    {
                        case Constants.ProtocolProcessType.Amendment:
                            processTypeDomain = FormsManagement.Constants.AmmendmentCategory.Domain;
                            break;
                        case Constants.ProtocolProcessType.AdverseEvent:
                            processTypeDomain = FormsManagement.Constants.AdverseEventCategory.Domain;
                            break;
                        case Constants.ProtocolProcessType.ContinuingReview:
                            processTypeDomain = FormsManagement.Constants.ContinuingReviewCategory.Domain;
                            break;
                        case Constants.ProtocolProcessType.OtherEvent:
                            processTypeDomain = FormsManagement.Constants.OtherEventCategory.Domain;
                            break;
                        default:
                            processTypeDomain = FormsManagement.Constants.EmergencyUseCategory.Domain;
                            break;
                    }

                    ArrayList questTypes = refCodes.GetSortedRefCodes(
                        processTypeDomain, "Order") ?? refCodes.GetRefCodes(processTypeDomain);

                    for (int i = 0, count = questTypes.Count; i < count; ++i)
                    {
                        RefCode code = (RefCode) questTypes[i];

                        QuestionnaireAnswer groupCode =
                            new QuestionnaireAnswer(cachePolicy);
                        groupCode.Id = -1;
                        groupCode.Name = code.Meaning;
                        gridArrayList.Add(groupCode);

                        bool added = false;

                        for (int j = 0, answerCount = answerList.Count; j < answerCount; ++j)
                        {
                            QuestionnaireAnswer currAns = (QuestionnaireAnswer) answerList[j];
                            if (currAns.QuestionnaireCategory == code.Code)
                            {
                                gridArrayList.Add(currAns);
                                added = true;
                            }
                        }

                        // remove the last one from the list, since there are none for this code and we don't 
                        // want to display empty ones.
                        if (!added)
                        {
                            gridArrayList.RemoveAt(gridArrayList.Count - 1);
                        }
                    }
                }

                if ((processType == Constants.ProtocolProcessType.InitialReview
                    && Protocol.ProtocolTypeCode == Constants.NewProtocolType.NewApplication) ||
                        processType == Constants.ProtocolProcessType.Amendment)
                {
                    // get the Ref Codes, and add them one by one, along with any in teh Answer List.
                    RefCodes refCodes = (RefCodes) applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);

                    ArrayList questTypes = refCodes.GetSortedRefCodes(
                        FormsManagement.Constants.CommonFormCategory.Domain, FormsManagement.Constants.CommonFormCategory.OrderAttribute);

                    for (int i = 0, count = questTypes.Count; i < count; ++i)
                    {
                        RefCode code = (RefCode) questTypes[i];

                        // we don't want to display the initial applications here if it's an initial review...
                        if ((code.Code == FormsManagement.Constants.CommonFormCategory.InitialApplication) &&
                            (processType == Constants.ProtocolProcessType.InitialReview))
                        {
                            continue;
                        }

                        QuestionnaireAnswer groupCode =
                            new QuestionnaireAnswer(cachePolicy);
                        groupCode.Id = -1;
                        groupCode.Name = code.Meaning;
                        gridArrayList.Add(groupCode);

                        bool added = false;

                        bool blankDeviceExists, blankSponsorExists, blankChildExists;
                        bool drugSectionActive, deviceSectionActive, childSectionActive;
                        bool blankDrugExists = blankDeviceExists = blankSponsorExists = blankChildExists =
                            drugSectionActive = deviceSectionActive = childSectionActive = false;

                        bool sponsorSectionActive = (processType == Constants.ProtocolProcessType.InitialReview);

                        string drugQuestionnaireName = string.Empty;
                        string deviceQuestionnaireName = string.Empty;
                        string childQuestionnaireName = string.Empty;
                        string sponsorQuestionnaireName = SponsorQuestionnaireName;

                        for (int j = 0, answerCount = answerList.Count; j < answerCount; ++j)
                        {
                            QuestionnaireAnswer currAns = (QuestionnaireAnswer) answerList[j];
                            if (currAns.QuestionnaireCategory == code.Code)
                            {
                                Questionnaire q = currAns.QuestionnaireVersion.Questionnaire;
                                if (q.Category == FormsManagement.Constants.CommonFormCategory.Drugs)
                                {
                                    drugSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Drugs;
                                        blankDrugExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Drugs)
                                    {
                                        blankDrugExists = true;
                                    }
                                    else
                                    {
                                        drugQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }
                                if (q.Category == FormsManagement.Constants.CommonFormCategory.Devices)
                                {
                                    deviceSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.QuestionnaireAnswerDefaultNames.MedicalDevices;
                                        blankDeviceExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.MedicalDevices)
                                    {
                                        blankDeviceExists = true;
                                    }
                                    else
                                    {
                                        deviceQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }
                                if ((q.Category == FormsManagement.Constants.CommonFormCategory.SpecialPop)
                                    && q.AllowMultiple)
                                {
                                    childSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Children;
                                        blankChildExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Children)
                                    {
                                        blankChildExists = true;
                                    }
                                    else
                                    {
                                        childQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }
                                if (q.Category == FormsManagement.Constants.CommonFormCategory.SponsorFunding)
                                {
                                    sponsorSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = (processType == Constants.ProtocolProcessType.Amendment) ?
                                                                                                                    FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM :
                                                                                                                                                                                             FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR;
                                        blankSponsorExists = true;
                                    }
                                    else if ((currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM) ||
                                        (currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR))
                                    {
                                        blankSponsorExists = true;
                                    }
                                    else
                                    {
                                        sponsorQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }
                                gridArrayList.Add(currAns);
                                added = true;
                            }
                        }

                        if ((code.Code == FormsManagement.Constants.CommonFormCategory.Drugs) &&
                            !blankDrugExists && drugSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.CommonFormCategory.Drugs,
                                FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Drugs, drugQuestionnaireName,
                                gridArrayList, FormsManagement.Constants.QuestionnaireType.Forms);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.CommonFormCategory.Devices) &&
                            !blankDeviceExists && deviceSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.CommonFormCategory.Devices,
                                FormsManagement.Constants.QuestionnaireAnswerDefaultNames.MedicalDevices,
                                deviceQuestionnaireName, gridArrayList, FormsManagement.Constants.QuestionnaireType.Forms);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.CommonFormCategory.SponsorFunding) &&
                            !blankSponsorExists && sponsorSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.CommonFormCategory.SponsorFunding,
                                FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM, sponsorQuestionnaireName,
                                gridArrayList, FormsManagement.Constants.QuestionnaireType.Forms);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.CommonFormCategory.SpecialPop) &&
                            !blankChildExists && childSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.CommonFormCategory.SpecialPop,
                                FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Children, childQuestionnaireName,
                                gridArrayList, FormsManagement.Constants.QuestionnaireType.Forms);
                            added = true;
                        }

                        // remove the last one from the list, since there are none for this code and we don't 
                        // want to display empty ones.
                        if (!added)
                        {
                            gridArrayList.RemoveAt(gridArrayList.Count - 1);
                        }
                    }
                }
                if (Protocol.ModuleType == Constants.ModuleType.Animals)
                {
                    // get the Ref Codes, and add them one by one, along with any in teh Answer List.
                    RefCodes refCodes = (RefCodes) applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);
                    ArrayList questTypes = refCodes.GetSortedRefCodes(FormsManagement.Constants.AnimalsFormCatgory.Domain, FormsManagement.Constants.AnimalsFormCatgory.OrderAttribute);

                    for (int i = 0, count = questTypes.Count; i < count; ++i)
                    {
                        RefCode code = (RefCode) questTypes[i];

                        // we don't want to display the initial applications here if it's an initial review...
                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.InitialApplication) &&
                            (processType == Constants.AnimalProtocolProcessType.InitialReview))
                        {
                            continue;
                        }

                        QuestionnaireAnswer groupCode =
                            new QuestionnaireAnswer(cachePolicy);
                        groupCode.Id = -1;
                        groupCode.Name = code.Meaning;
                        gridArrayList.Add(groupCode);

                        bool added = false;
                        bool blankProceduresExists, blankTumorExists, blankSponsorExists, blankAnesthesiaExists;
                        bool proceduresSectionActive, anesthesiaSectionActive, tumorSectionActive;
                        bool blankHazardousExists = blankProceduresExists = blankAnesthesiaExists = blankTumorExists = blankSponsorExists = false;
                        bool hazardousSectionActive = proceduresSectionActive = anesthesiaSectionActive = tumorSectionActive = false;

                        bool sponsorSectionActive = (processType == Constants.AnimalProtocolProcessType.InitialReview);

                        string hazardousQuestionnaireName = string.Empty;
                        string tumorQuestionnaireName = string.Empty;
                        string proceduresQuestionnaireName = string.Empty;
                        string anesthesiaQuestionnaireName = string.Empty;
                        string sponsorQuestionnaireName = SponsorQuestionnaireName;

                        for (int j = 0, answerCount = answerList.Count; j < answerCount; ++j)
                        {
                            QuestionnaireAnswer currAns = (QuestionnaireAnswer) answerList[j];
                            if (currAns.QuestionnaireCategory == code.Code)
                            {
                                Questionnaire q = currAns.QuestionnaireVersion.Questionnaire;
                                if (q.Category == FormsManagement.Constants.AnimalsFormCatgory.Hazardous)
                                {
                                    hazardousSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous;
                                        blankHazardousExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous)
                                    {
                                        blankHazardousExists = true;
                                    }
                                    else
                                    {
                                        hazardousQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }

                                // Tumor and procedures are both in common forms, so we need to key off name
                                if (q.Category == FormsManagement.Constants.AnimalsFormCatgory.TumorProduction)
                                {
                                    tumorSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor;
                                        blankTumorExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor)
                                    {
                                        blankTumorExists = true;
                                    }
                                    else
                                    {
                                        tumorQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }

                                if (q.Category == FormsManagement.Constants.AnimalsFormCatgory.Procedures && q.AllowMultiple)
                                {
                                    proceduresSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures;
                                        blankProceduresExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures)
                                    {
                                        blankProceduresExists = true;
                                    }
                                    else
                                    {
                                        proceduresQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }

                                if (q.Category == FormsManagement.Constants.AnimalsFormCatgory.Anesthesia && q.AllowMultiple)
                                {
                                    anesthesiaSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Anesthesia;
                                        blankAnesthesiaExists = true;
                                    }
                                    else if (currAns.Name == FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Anesthesia)
                                    {
                                        blankAnesthesiaExists = true;
                                    }
                                    else
                                    {
                                        anesthesiaQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }

                                if (q.Category == FormsManagement.Constants.AnimalsFormCatgory.SponsorFunding)
                                {
                                    sponsorSectionActive = true;
                                    if (currAns.Name == q.Name)
                                    {
                                        currAns.Name = (processType == Constants.AnimalProtocolProcessType.Amendment) ?
                                                                                                                          FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM :
                                                                                                                                                                                                   FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR;
                                        blankSponsorExists = true;
                                    }
                                    else if ((currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM) ||
                                        (currAns.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR))
                                    {
                                        blankSponsorExists = true;
                                    }
                                    else
                                    {
                                        sponsorQuestionnaireName = currAns.QuestionnaireVersion.Questionnaire.Name;
                                    }
                                }

                                gridArrayList.Add(currAns);
                                added = true;
                            }
                        }

                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.Hazardous) &&
                            !blankHazardousExists && hazardousSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.AnimalsFormCatgory.Hazardous,
                                FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous,
                                hazardousQuestionnaireName, gridArrayList, FormsManagement.Constants.QuestionnaireType.Animals);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.TumorProduction) &&
                            !blankTumorExists && tumorSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.AnimalsFormCatgory.TumorProduction,
                                FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor,
                                tumorQuestionnaireName, gridArrayList, FormsManagement.Constants.QuestionnaireType.Animals);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.Procedures) &&
                            !blankProceduresExists && proceduresSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.AnimalsFormCatgory.Procedures,
                                FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures,
                                proceduresQuestionnaireName, gridArrayList, FormsManagement.Constants.QuestionnaireType.Animals);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.Anesthesia) &&
                            !blankAnesthesiaExists && anesthesiaSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.AnimalsFormCatgory.Anesthesia,
                                FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Anesthesia,
                                anesthesiaQuestionnaireName, gridArrayList, FormsManagement.Constants.QuestionnaireType.Animals);
                            added = true;
                        }

                        if ((code.Code == FormsManagement.Constants.AnimalsFormCatgory.SponsorFunding) &&
                            !blankSponsorExists && sponsorSectionActive && !ProtocolProcess.Locked)
                        {
                            HandleBlankQuestionnaireAnswer(FormsManagement.Constants.AnimalsFormCatgory.SponsorFunding,
                                FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM, sponsorQuestionnaireName,
                                gridArrayList, FormsManagement.Constants.QuestionnaireType.Animals);
                            added = true;
                        }

                        // remove the last one from the list, since there are none for this code and we don't 
                        // want to display empty ones.
                        if (!added)
                        {
                            gridArrayList.RemoveAt(gridArrayList.Count - 1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
                formsGrid.Enabled = false;
                addDeleteForms.Visible = false;
                deleteApp.Enabled = false;
            }
            return gridArrayList;
        }

        /// <summary>
        /// Creates a new "blank questionnaire answer for the particular questionnaire 
        /// (multiples only) and adds it to the grid (does NOT add it to the protocol
        /// version b/c there will always be a link there that the user doesn't want added)
        /// </summary>
        /// <param name="category">category the questionnaireanswer belongs to</param>
        /// <param name="addText">text to display to the user for adding a new one</param>
        /// <param name="questionnaireName"></param>
        /// <param name="gridArrayList">list to populate the questionnaireanswer with </param>
        /// <param name="questionnaireType"></param>
        private void HandleBlankQuestionnaireAnswer(string category, string addText,
            string questionnaireName, ArrayList gridArrayList, string questionnaireType)
        {
            QuestionnaireAnswer newAnswer = new QuestionnaireAnswer(cachePolicy);
            newAnswer.QuestionnaireCategory = category;
            newAnswer.Name = addText;
            newAnswer.Id = 0;
            newAnswer.QuestionnaireVersion = Questionnaire.GetActiveVersion(
                cachePolicy, questionnaireName, questionnaireType);

            if (null != newAnswer.QuestionnaireVersion)
            {
                newAnswer.QuestionnaireVersionId = newAnswer.QuestionnaireVersion.Id;
                gridArrayList.Add(newAnswer);
            }
        }

        /// <summary>
        /// OnItemCommand is fired when the link for a QuestionnaireANswer is clicked. In certain cases,
        /// ex. Drugs, Sponsors, etc., we want to fire a different page first, instead of the 
        /// 'AnswerQuestionnairePage' page. FOr example, we fire the sponsor or drug selection page in the case 
        /// where a drug or sponsor has not yet been selected for this quesitonnaireAnswer.
        /// </summary>
        /// <param name="source">The control which raised the event.</param>
        /// <param name="e">Arguments assocoiated with the event</param>
        private void OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "SelectForm")
                {
                    QuestionnaireAnswer qA = (QuestionnaireAnswer) gridArrayList[e.Item.ItemIndex];
                    Questionnaire q = qA.QuestionnaireVersion.Questionnaire;

                    bool removeQAOnCancel = false;
                    if ((qA.Id == 0) && qA.Answers.Count == 0)
                    {
                        qA.Action = (int) QuestionnaireAnswer.UserAction.Edit;
//						qA = ProtocolVersion.AddNewQuestionnaireAnswer(qA.QuestionnaireVersionId,	cachePolicy, qA.QuestionnaireVersion.Questionnaire.Name, false);
                        ProtocolVersion.QuestionnaireAnswers.Add(qA);

                        //Need to insert the mapping record and as such the Save() on ProtocolVersion is invoked
                        //instead of the Save() on the QuestionnaireAnswer.
                        //qA.Save(Utility.DataAccess.ConnectionString);
                        ProtocolVersion.Save(DataAccess.ConnectionString);

                        removeQAOnCancel = true;
                    }

                    qA.Cache();

                    Hashtable outgoingData = new Hashtable();
                    outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                    outgoingData.Add(Keys.ProtocolProcessIdKey, protocolProcessId);
                    outgoingData.Add(Keys.ProtocolVersionIdKey, ProtocolVersion.Id);
                    outgoingData.Add(Keys.QuestionnaireVersionIdKey, qA.QuestionnaireVersionId);
                    outgoingData.Add(Keys.QuesionnaireAnswerIdKey, qA.Id);
                    outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                    outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
                    outgoingData.Add(Keys.RemoveQAOnCancel, removeQAOnCancel);
                    pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

                    if (q.Category == FormsManagement.Constants.CommonFormCategory.Drugs && qA.Name ==
                        FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Drugs)
                    {
                        Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.DrugSelectionPageURL", ""), false);
                    }
                    else if (q.Category == FormsManagement.Constants.CommonFormCategory.Devices &&
                        qA.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.MedicalDevices)
                    {
                        Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.DeviceSelectionPageURL", ""), false);
                    }
                    else if ((q.Category == FormsManagement.Constants.CommonFormCategory.SponsorFunding) &&
                        ((qA.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM) ||
                            (qA.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR)))
                    {
                        Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.SponsorSelectionPageURL", ""), false);
                    }
                    else if ((q.Category == FormsManagement.Constants.AnimalsFormCatgory.SponsorFunding) &&
                        ((qA.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_AM) ||
                            (qA.Name == FormsManagement.Constants.QuestionnaireAnswerDefaultNames.Sponsor_IR)))
                    {
                        Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.SponsorSelectionPageURL", ""), false);
                    }
                    else
                    {
                        Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.AnswerQuestionnairePageURL", ""), false);
                    }
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
                formsGrid.Enabled = false;
                addDeleteForms.Visible = false;
                deleteApp.Enabled = false;
            }
        }

        /// <summary>
        /// Marks the QA for editing or not, based on the user's selected action, and rebinds the grid
        /// to reflect the choice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnFormActionChange(Object sender, EventArgs e)
        {
            RadioButtonList list = (RadioButtonList) sender;

            QuestionnaireAnswer answer = (QuestionnaireAnswer) gridArrayList[
                ((DataGridItem) list.Parent.Parent).ItemIndex];
            answer.Action =
                Convert.ToInt32(list.SelectedValue);
            answer.Save(DataAccess.ConnectionString);

            gridArrayList = PopulateGridQuestionnaireList( );

            pageCache[QuestionnaireListKey] = gridArrayList;
            pageCachePolicy.Cache(PageCacheKey, pageCache);

            formsGrid.DataSource = gridArrayList;
            formsGrid.DataBind();
        }


        /// <summary>
        /// OnAddDeleteFormsClick is fired when the user clicks the 'AddDeleteForms' button. 
        /// this launches the AddDeleteForms page.
        /// </summary>
        /// <param name="sender">The control which raised the event.</param>
        /// <param name="e">Arguments assocoiated with the event</param>
        private void OnAddDeleteFormsClick(object sender, CommandEventArgs e)
        {
            try
            {
                // cache some things
                Hashtable outgoingData = new Hashtable();
                outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                outgoingData.Add(Keys.ProtocolProcessIdKey, protocolProcessId);
                outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                outgoingData.Add(Keys.ShowAsPopUp, showAsPopUp);
                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

                // now that it's saved, redirect the user to the ProtocolProcessOverview page.
                Page.Response.Redirect(
                    Settings.GetKeyValue("SubModuleNavigation.Humans.AddDeleteFormsURL", ""), false);
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
                formsGrid.Enabled = false;
                addDeleteForms.Visible = false;
                deleteApp.Enabled = false;
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            humansSubModNavigation.Reset();
        }

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            humansSubModNavigation.Reset();
        }

        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate(object sender, EventArgs e)
        {
            OnHumansSubModNavigate();
        }

        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate()
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, pageCache[ProtocolIdKey]);
            outgoingData.Add(Keys.ProtocolProcessIdKey, pageCache[ProtocolProcessIdKey]);
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
        }

        /// <summary>
        /// caches the outgoing data and redirects to the editProtocolInfo page
        /// </summary>
        /// <param name="sender">control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnEditProtocolClick(object sender, EventArgs e)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, pageCache[ProtocolIdKey]);
            outgoingData.Add(Keys.ProtocolProcessIdKey, pageCache[ProtocolProcessIdKey]);
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.EditProtocolInfoPageURL", ""));
        }

        /// <summary>
        /// Marks the Protocol for deletion if the user has the appropriate permissions, they can click it.
        /// </summary>
        /// <param name="sender">control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnDeleteProtocol(object sender, ImageClickEventArgs e)
        {
            if (confirmDelete)
            {
                if (ProtocolProcess.Type == Constants.ProtocolProcessType.InitialReview ||
                    ProtocolProcess.Type == Constants.AnimalProtocolProcessType.InitialReview)
                {
                    Protocol.MarkForDelete = true;
                    Protocol.Save(DataAccess.GetConnectionString());

                    //if protocol has been submitted, change its status to Finished
                    DataAccess.ExecuteNonQuery(DataAccess.GetConnectionString(),
                        "UpdateProtocolProcessForDeletedProtocols",
                        DataAccess.BuildSqlParameterArray("ProtocolProcessId",
                            SqlDbType.Int,
                            protocolProcessId));
                }
                else
                {
                    ProtocolProcess.Delete(DataAccess.GetConnectionString());
                }

                // redirect to the referrer(top level source page).
                Response.Redirect(ReferringPage);
            }
        }

        /// <summary>
        /// Clones the current protocol and navigates to the new protocol.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCloneProtocol(object sender, ImageClickEventArgs e)
        {
            UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;

            bool includeStaff = cloneOptions.Items[0].Selected;
            bool includeAttachments = cloneOptions.Items[1].Selected;
            Protocol clone = Protocol.Clone(includeStaff, includeAttachments, userContext.DomainUserId);

            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, clone.Id);
            outgoingData.Add(Keys.ProtocolProcessIdKey, pageCache[Keys.ProtocolProcessIdKey]);
            outgoingData.Add(Keys.ProtocolAccessKey, pageCache[Keys.ProtocolAccessKey]);
            outgoingData.Add(Keys.PageReferrerKey, "ProtocolDetails");
            outgoingData.Add("IsClone", true);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            Page.Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.EditProtocolInfoPageURL", ""));
        }

        /// <summary>
        /// Registers a hidden field used to determine on page load whether to refresh the confirmDelete javascript.
        /// </summary>
        /// <param name="e">arguments to render.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            ClientScript.RegisterHiddenField(DeleteConfirmationFlag, confirmDelete.ToString());
            if (ProtocolProcess.Type == Constants.ProtocolProcessType.InitialReview ||
                ProtocolProcess.Type == Constants.AnimalProtocolProcessType.InitialReview)
            {
                OtherInstructions.Visible = false;
                AmendmentInstructions.Visible = false;
            }
            else if (ProtocolProcess.Type == Constants.ProtocolProcessType.Amendment ||
                ProtocolProcess.Type == Constants.AnimalProtocolProcessType.Amendment)
            {
                IRinstructions.Visible = false;
                OtherInstructions.Visible = false;
            }
            else
            {
                IRinstructions.Visible = false;
                AmendmentInstructions.Visible = false;
            }
        }

        #region Web Form Designer generated code

        /// <summary>
        /// Handler for the event raised when the page is being initialized.
        /// Retrieve the cache policy in force.
        /// </summary>
        /// <param name="e">Arguments assocoiated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            applicationCachePolicy = (Policy.ICachePolicy) Application[Policy.Names.ApplicationCachePolicyKey];
            viewStateCachePolicy = new PHSRAG.Insight21.Policy.ViewStateCachePolicy(this.ViewState);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.humansSubModNavigation.Navigate += new PHSRAG.Insight21.InsightWebControls.HumansSubModuleNavigation.NavigateEventHandler(this.OnHumansSubModNavigate);
            this.animalsSubModNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnHumansSubModNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.formsGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnItemCommand);
            this.formsGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
            this.addDeleteForms.Command += new CommandEventHandler(OnAddDeleteFormsClick);
            this.deleteApp.Click += new ImageClickEventHandler(OnDeleteProtocol);
            cloneProtocol.Click += new ImageClickEventHandler(OnCloneProtocol);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Nested type: ColumnIndex

        private enum ColumnIndex
        {
            Id, // hidden
            QuestionnaireVersionId, // hidden
            SelectForm,
            FormAction,
            LastModifiedDate
        }

        #endregion
    }
}